#include "stm32f4xx_hal.h"
#include "usart.h"

#include "amt1450_uart.h"


uint8_t rxBuffer = 0;
amt1450_UART_Rx_t amt1450_UART_Rx;


void Init_AMT1450_UART(void) {
	HAL_UART_Receive_IT(&AMT1450_uart, &rxBuffer, 1); // 使能uart中断
}


/**
 * @brief: SUM校验
 * @param: {type}
 * @retval: None
 */
uint8_t Check_Sum(uint8_t* pData, uint8_t length) {
	uint16_t sum = 0;
	for(uint8_t i=0; i<length - 1;i++) {
		sum += pData[i];
	}
	if((uint8_t)sum == pData[length - 1]) return 1;
	return 0;
}


/**
 * @brief: 一个字节中断接收
 * @param: {type} 
 * @retval: None
 */
void UART_GetChar(uint8_t pData) {
	// 串口 
	if(amt1450_UART_Rx.RxDataPtr >= 9) {
		amt1450_UART_Rx.RxDataPtr= 0;
		return;
	}
	if(amt1450_UART_Rx.RxDataPtr == 0 && pData == AMT1450_FRAME_START){        // 帧头
		amt1450_UART_Rx.RxData[amt1450_UART_Rx.RxDataPtr++] = pData;
	}
  else if(amt1450_UART_Rx.RxDataPtr == 1)  {
		amt1450_UART_Rx.RxData[amt1450_UART_Rx.RxDataPtr++] = pData;      // num
	}
	else if(amt1450_UART_Rx.RxDataPtr < ((amt1450_UART_Rx.RxData[1]&0x0f)+3)){
		amt1450_UART_Rx.RxData[amt1450_UART_Rx.RxDataPtr++] = pData;
		// 
		if(amt1450_UART_Rx.RxDataPtr == ((amt1450_UART_Rx.RxData[1]&0x0f)+3)){ // 接收完成
			// 校验
			if(Check_Sum(amt1450_UART_Rx.RxData, amt1450_UART_Rx.RxDataPtr)){
				for(uint8_t i = 0; i<((amt1450_UART_Rx.RxData[1]&0x0f) + 3); i++) {
					amt1450_UART_Rx.ValidData[i] = amt1450_UART_Rx.RxData[i];		// 数据存储
					// printf ("%d\n", amt1450_UART_Rx.ValidData[1]&0x0f);
				}
			}
			amt1450_UART_Rx.RxDataPtr = 0;
		}
	}
	else amt1450_UART_Rx.RxDataPtr = 0;
}


/**
 * @brief:  获取amt1450数据（压缩数据）
 * @param:  {type}
 * @retval: None
 */
void Get_AMT1450Data_UART(uint8_t *begin_Color,uint8_t *jump_Count,uint8_t *jump_Location) {
	*begin_Color = (amt1450_UART_Rx.ValidData[1] & 0x80) >>7;
	*jump_Count = amt1450_UART_Rx.ValidData[1] & 0x0f;
	for (uint8_t i = 0; i < *jump_Count; i++){
		jump_Location[i] = amt1450_UART_Rx.ValidData[2+i];
	}
}


// 测试AMT1450功能
void AMT1450_Test_UART(uint8_t *begin_Color,uint8_t *jump_Count,uint8_t *jump_Location) {
	static uint8_t position;
	while(1){
		Get_AMT1450Data_UART(begin_Color, jump_Count, jump_Location);
		if(*jump_Count == 2) position = 0.5f * (jump_Location[0] + jump_Location[1]);
		HAL_Delay(10);
	}
}


/**
 * @brief: 接收中断
 * @param: {type} 
 * @retval: None
 */
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) {
	if(huart == &AMT1450_uart) {
		UART_GetChar(rxBuffer);
		HAL_UART_Receive_IT(&AMT1450_uart, &rxBuffer, 1);
	}
}


